<?php

namespace app\api\controller;
use GuzzleHttp\Client;
class NewMid extends \app\BaseController
{
    public function chat()
    {
        $post = $this->request->post();
        $header = 'sk-cO53c8hYNGfKnC5q6fFd1a964f7e42C6AcFbB51e2a0dCe90';

        $client = new Client([
                'base_uri' => 'https://ai.ruancc.com/v1/chat/completions',
                // You can set any number of default request options.
                'timeout' => 600,
            ]
        );

        try{
            if(isset($post['stream']) && $post['stream']){
                header('X-Accel-Buffering: no');
                header('Cache-Control: no-cache');
                header('Content-Type: text/plain; charset=utf-8');
                set_time_limit(0); //防止超时
                ob_end_clean();
                ob_implicit_flush(1);
                $res = $client->request('post', '', [
                    'verify' => false,
                    'headers' => ['Authorization'=>$header],
                    'stream' => true,
                    'json' => $post,
                ]);

                $body = $res->getBody();
                while (!$body->eof()) {
                    echo $body->read(256);
                }
            }else{
                $res = $client->request('post', '', [
                    'verify' => false,
                    'headers' => ['Authorization'=>$header],
                    'json' => $post,
                ]);
                return $res;
            }



        }catch (\Exception $e) {
            throw $e;
        }


    }
}